#pragma once

#include <iostream>
#include <fcntl.h>
#include <vector>
#include "Protocol.hpp"

namespace ns_util
{
  void SetNoBlock(int fd)
  {
    // 提取出fd的文件状态标志位
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0){
      std::cerr << "fcntl error" << std::endl;
      return;
    }
    // 将标志位设置为非阻塞
    fcntl(fd, F_SETFL, fl|O_NONBLOCK);
  }
  
  void Split(std::string& in, std::vector<std::string>& out)
  {
    size_t pos;
    while((pos=in.find('?'))!=std::string::npos){
      // '?'作为分隔符
      // 提取前pos个字符
      out.push_back(in.substr(0, pos));
      // 去除前pos+1个字符
      in.erase(0, pos+1);
    }
  }
  int my_stoi(std::string s)
  {
    auto it = s.begin();
    if (s[0] == '-')
      ++it;
    std::string res;
    while (it != s.end()){
      if (*it >= '0' && *it <= '9')
        res += *it;
      ++it;
    }

    return stoi(res);
  }
  void Deserialize(std::string& in, request& rq)
  {
    int pos = 0;
    for(auto ch : in)
    {
      if (ch == '+' || ch == '-' || ch == '*' || ch == '/'){
        rq._num1 = my_stoi(in.substr(0, pos).c_str());
        rq._op = ch;
        rq._num2 = my_stoi(in.substr(pos+1).c_str());
        break;
      }
      pos++;
    }
  }
}
